# usage: "train" or "submit"
import sys

class ReIndexer:
	def __init__(self):
		self.id2indx = {}
		self.tot_num = 0
		self.indx_list = []


	def build_index(self, iprofname, uprofname):
		print 'build index for items'
		
		iprof = open(iprofname)
		for line in iprof:
			iid = int(line.split()[0])
			if not iid in self.id2indx:
				self.id2indx[iid] = self.tot_num
				self.indx_list.append((iid, self.tot_num))
				self.tot_num += 1
		iprof.close()
		
		print 'build index for users'
		uprof = open(uprofname)
		for line in uprof:
			uid = int(line.split()[0])	
			if not uid in self.id2indx:
				self.id2indx[uid] = self.tot_num
				self.indx_list.append((uid, self.tot_num))
				self.tot_num += 1
		uprof.close()
		
	def reindex(self, ifname, ofname, name_cols):
		print 'reindexing %s' % (ifname, )
		ifile = open(ifname)
		ofile = open(ofname,'w')
		
		for line in ifile:
			cols = line.strip().split('\t')
			
			for c in name_cols:
				cols[c] = str(self.id2indx[int(cols[c])])
			ofile.write('\t'.join(cols)+'\n')
		
		ifile.close()
		ofile.close()
	
	def save_index(self, ofname):
		ofile = open(ofname, 'w')
		for (k, v) in self.indx_list:
			ofile.write('%d -> %d\n' % (k, v))
		ofile.close()
		
	

if __name__ == '__main__':
	indexer = ReIndexer()
	indexer.build_index('item.txt', 'user_profile.txt')
	indexer.save_index('new_index.txt')
	
        
	indexer.reindex('item.txt', 'item.ridx', [0])
	indexer.reindex('user_action.txt', 'user_action.ridx', [0, 1])
	indexer.reindex('user_key_word.txt', 'user_key_word.ridx', [0])
	indexer.reindex('user_profile.txt', 'user_profile.ridx',[0])
	indexer.reindex('user_sns.txt', 'user_sns.ridx',[0, 1])

	if sys.argv[1] == "train":
                indexer.reindex('train.txt', 'train.ridx', [0, 1])
                indexer.reindex('test.txt', 'test.ridx', [0, 1])
                indexer.reindex('rec_log_train_newlabel.txt', 'rec_log_train.ridx', [0, 1])
                indexer.reindex('rec_log_test_newlabel.txt', 'rec_log_test.ridx', [0, 1])

	if sys.argv[1] == "evalset":
                indexer.reindex('rec_log_train_newlabel.txt', 'rec_log_train.ridx', [0, 1])
                indexer.reindex('rec_log_test_newlabel.txt', 'rec_log_test.ridx', [0, 1])
